package by.cooker.persdic;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @author cooker
 */
public class Dictionary {
	private ArrayList<Word> dictionary;

	public ArrayList<Word> getDictionary() {
		if (dictionary == null) {
			dictionary = new ArrayList<Word>();
		}
		return dictionary;
	}

	public Dictionary() {
		getDictionary();
	}

	public void removeAllWords() {
		dictionary.removeAll(getDictionary());
	}

	public void addWord(Word word) {
		if (word == null) {
			throw new IllegalArgumentException("word=" + word);
		}
		dictionary.add(word);
	}

	public void exportWordsDataBase(File database) {

		try {
			PrintWriter dbSaver = new PrintWriter(database);
			StringBuilder sb = new StringBuilder();
			for (Word w : dictionary) {
				sb.append(w.getWordId());
				sb.append(";");
				sb.append(w.getText());
				sb.append(";");
				sb.append(w.getTranscription());
				sb.append(";");
				String[] data = w.getTranslate();
				for (String element : data) {
					sb.append(element);
					sb.append(" ");
				}
				dbSaver.println(sb.toString());
				sb.setLength(0);
			}
			dbSaver.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ArrayList<Word> getAllWords() {
		return dictionary;
	}

	public Word getWord(String word) {
		for (Word w : dictionary) {
			if (word.equals(w.getText())) {
				return w;
			}
		}
		return null;
	}

	public void importWordsDataBase(File database) {
		try {
			Scanner dbReader = new Scanner(database);
			while (dbReader.hasNext()) {
				Word w = serachWord(dbReader.nextLine());
				dictionary.add(w);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void removeWord(String word) {
		for (Word w : dictionary) {
			if (word.equals(w.getText())) {
				if (dictionary.isEmpty()) {
					dictionary.remove(w);
				}
			}
		}
	}

	private Word serachWord(String str) {
		String[] snippets = str.split(";");
		String[] translates = snippets[3].toString().split(" ");

		return new Word(Integer.parseInt(snippets[0]), snippets[1],
				snippets[2], translates);
	}

}
